﻿using DotnetSpider.Core;
using DotnetSpider.Core.Processor;
using HtmlAgilityPack;
using Spider_Demo.Models;
using System;
using System.Collections.Generic;
using System.Text;

namespace Spider_Demo.PageProcesser
{
    public class NetBiAn_Processor : BasePageProcessor
    {
        protected override void Handle(Page page)
        {
            List<BiAn_Images> list = new List<BiAn_Images>();
            var modelHtmlList = page.Selectable.XPath("//*[@id='main']/div[3]/ul/li/a").Nodes();
            foreach (var modelHtml in modelHtmlList)
            {
                GetInfo(modelHtml.XPath("./@href").GetValue(), out string ImgUrl, out string ImgType);

                BiAn_Images entity = new BiAn_Images
                {
                    ImgTitle = modelHtml.XPath("./b").GetValue(),
                    ImgType = ImgType,
                    HD_ImgUrl = ImgUrl
                };
                //page.AddTargetRequest(entity.ImgUrl); //Site设置DownloadFiles为TRUE就可以自动下载文
                list.Add(entity);
            }
            page.AddResultItem("BiAn_ImgList", list);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="Url">详情页Url地址</param>
        /// <param name="ImgUrl">图片路径</param>
        /// <param name="ImgType">图片类型</param>
        private void GetInfo(string Url, out string ImgUrl, out string ImgType)
        {
            HtmlWeb htmlWeb = new HtmlWeb
            {
                OverrideEncoding = Encoding.GetEncoding("gb2312")//编码
            };
            var dochtml = htmlWeb.Load(Url);
            string ImgTypeText = dochtml.DocumentNode.SelectSingleNode("//*[@id='main']/div[2]/div[2]//p[1]/span/a").InnerText;
            if (string.IsNullOrEmpty(ImgTypeText))
            {
                ImgType = "其他";
            }
            else
            {
                ImgType = ImgTypeText;
            }
            ImgUrl = "http://pic.netbian.com" + dochtml.DocumentNode.SelectSingleNode("//*[@id='img']/img").Attributes["src"].Value;
        }
    }
}
